import { createStore } from 'vuex';

const store = createStore({
    state: {
        isLoggedIn: false,
        cartItems: []
    },
    mutations: {
        setLoggedIn(state, value) {
            state.isLoggedIn = value;
        },
        addToCart(state, product) {
            const existingItem = state.cartItems.find(item => item.product.id === product.id);
            if (existingItem) {
                existingItem.quantity++;
            } else {
                state.cartItems.push({
                    product,
                    quantity: 1
                });
            }
        },
        removeFromCart(state, productId) {
            const index = state.cartItems.findIndex(item => item.product.id === productId);
            if (index > -1) {
                state.cartItems.splice(index, 1);
            }
        },
        clearCart(state) {
            state.cartItems = [];
        }
    },
    actions: {
        addToCart({ commit }, product) {
            commit('addToCart', product);
        }
    },
    getters: {
        totalPrice(state) {
            return state.cartItems.reduce((total, item) => total + (item.product.price * item.quantity), 0);
        }
    }
});

export default store;